import React, { useState, useCallback } from 'react';
import { debounce } from 'lodash';
import { Input, Form, Popconfirm, Spin, Tooltip } from 'antd';
import BizIcon from '@/components/BizIcon';
import cn from 'classnames';
import { focusInTheEndOfInput } from '@/pages/Recruitment/utils.js';
import styles from './index.less';

/**
 * 避免影响其它地方的 CustomAdd ，因此新增本组件。
 */
const CustomAddV2 = ({
    inputRef,
    value,
    form,
    handleAutoSave,
    onChange,
    disabled,
    loading,
    interviewLoading,
    ...rest
}) => {
    const [localEmployeeName] = useState(JSON.parse(localStorage.getItem('user') || null)?.employeeName);
    const [allowAdd, setAllowAdd] = useState(true);
    const { getFieldDecorator, getFieldValue, setFieldsValue, validateFields } = form;

    React.useEffect(() => {
        if (value?.length === 1 && value[0].id === '') {
            console.log(
                '====================针对无问题 + 无评估表，会有一个默认值，有这个默认值的时候，不允许点击添加====================>'
            );
            setAllowAdd(false); // 针对无问题 + 无评估表，会有一个默认值，有这个默认值的时候，不允许点击添加
        } else {
            console.log('允许添加');
            setAllowAdd(true);
        }
    }, [interviewLoading]);

    /**
     * 把问题变成待编辑状态
     */
    const changeQuestionToEdit = sort => {
        setAllowAdd(false);
        onChange([
            ...value.slice(0, sort),
            {
                question: value[sort].question,
                sort: '',
                edit: true,
                id: value[sort].id,
                quesType: 'self'
            },
            ...value.slice(sort + 1)
        ]);
        setTimeout(() => {
            focusInTheEndOfInput(inputRef);
        }, 0);
    };
    const handleDelete = sort => {
        const lists = getFieldValue('interviewQuestion');
        console.log('handleDelete: ', sort);
        const removedItem = value[sort];
        // eslint-disable-next-line guard-for-in,no-restricted-syntax
        for (const index in lists) {
            const nIndex = Number(index);
            if (nIndex >= sort && lists[nIndex + 1]) {
                setFieldsValue({
                    [`interviewQuestion[${nIndex}]`]: lists[nIndex + 1]
                });
            }
        }
        const newValue = [...value.slice(0, sort), ...value.slice(sort + 1)].map((item, index) => ({
            question: item.question,
            sort: index + 1,
            edit: item.edit,
            id: item.id,
            createUserName: item.createUserName || '',
            quesType: item.quesType
        }));
        onChange(newValue);
        handleAutoSave(removedItem, 1);
        setTimeout(() => {
            setAllowAdd(true);
        }, 100);
    };
    /**
     * 失焦时触发自动保存
     * @param {number} sort --对应项目的数组下标
     */
    const handleAddInput = debounce(
        sort => {
            validateFields([`interviewQuestion[${sort}].title`], err => {
                if (!err) {
                    const newItem = {
                        question: getFieldValue(`interviewQuestion[${sort}].title`),
                        sort: '',
                        edit: false,
                        id: value[sort].id,
                        quesType: 'self'
                    };
                    const newValue = [...value.slice(0, sort), newItem, ...value.slice(sort + 1)].map(
                        (item, index) => ({
                            ...item,
                            sort: index + 1
                        })
                    );
                    onChange(newValue);
                    handleAutoSave(newItem, 0);
                    setTimeout(() => {
                        setAllowAdd(true);
                    }, 100);
                }
            });
        },
        {
            wait: 1000,
            leading: true,
            trailing: false
        }
    );
    // const handleCancel = (sort, text) => {
    //     if (text) {
    //         onChange([
    //             ...value.slice(0, sort),
    //             {
    //                 question: value[sort].question,
    //                 sort: '',
    //                 edit: false,
    //                 id: value[sort].id,
    //                 quesType: 'self'
    //             },
    //             ...value.slice(sort + 1)
    //         ]);
    //     } else {
    //         handleDelete(sort);
    //     }
    // };
    const handleAddPanel = useCallback(() => {
        if (!allowAdd) {
            return;
        }
        console.log('===========handleAddPanel================allowAdd====================>', allowAdd);

        setAllowAdd(false);
        onChange([
            ...value,
            {
                question: '',
                sort: '',
                edit: true,
                id: '',
                quesType: 'self'
            }
        ]);
    }, [allowAdd, value]);
    const renderName = item => (
        <div className={styles.Right}>
            <span className={styles.createUser}>
                <i className={cn('iconfont', 'iconcountpeople_o', styles.createUserIcon)} />
                {item.createUserName || item?.createUserInfo?.employeeName || localEmployeeName}
            </span>
        </div>
    );

    /**
     * 处理非编辑状态下问题的点击
     */
    const handleQuestionClick = (index, item) => {
        if (!disabled && item.quesType !== 'other') {
            changeQuestionToEdit(index);
        }
    };

    return (
        <Spin spinning={loading}>
            {value.map((item, index) => (
                // 这个key = editing 的情况，只会在编辑状态下出现，只会出现在一个项目中，因此直接写死没问题，不会重复。这样dom复用，input的焦点不会变
                <div key={item.id || 'editing'}>
                    <Form.Item>
                        {getFieldDecorator(`interviewQuestion[${index}].hide`)(
                            <div className={cn(styles.panel, item.edit ? styles.flexAlign : null)} {...rest}>
                                <span style={{ lineHeight: '32px' }}>{index + 1}</span>
                                {/* 问题编辑 or 展示 */}
                                {!item.edit ? (
                                    <>
                                        <div
                                            className={cn(
                                                styles.questionBase,
                                                disabled || item.quesType === 'other'
                                                    ? styles.questionNoHover
                                                    : styles.questionAllowHover
                                            )}
                                            onClick={() => {
                                                handleQuestionClick(index, item);
                                            }}
                                        >
                                            <span>
                                                {item.question}
                                                <span className={styles.iconWrapper}>
                                                    <i
                                                        className={cn(
                                                            'iconfont iconlistfunction_edit_icon_default',
                                                            styles.iconHover
                                                        )}
                                                    />
                                                </span>
                                            </span>
                                        </div>
                                        {renderName(item, index)}
                                    </>
                                ) : (
                                    <div className={styles.inputView}>
                                        <Form.Item label="" required style={{ width: '100%' }}>
                                            {getFieldDecorator(`interviewQuestion[${index}].title`, {
                                                initialValue:
                                                    item.question || getFieldValue(`interviewQuestion[${index}].hide`),
                                                rules: [
                                                    { required: true, message: '请输入面试问题标题!' },
                                                    { max: 100, message: '面试问题不能超过100个字符' }
                                                ]
                                            })(
                                                <Input.TextArea
                                                    autoSize
                                                    ref={node => {
                                                        inputRef.current = node;
                                                    }}
                                                    onBlur={() => {
                                                        handleAddInput(index);
                                                    }}
                                                    onPressEnter={() => {
                                                        handleAddInput(index);
                                                    }}
                                                    className={styles.customInput}
                                                    style={{
                                                        fontSize: '14px',
                                                        marginLeft: '8px',
                                                        resize: 'none'
                                                    }}
                                                />
                                            )}
                                        </Form.Item>
                                    </div>
                                )}
                                {item.quesType === 'self' && !disabled ? (
                                    <>
                                        <div className={styles.placeHolder}></div>
                                        <div className={styles.removeBtn}>
                                            <Popconfirm
                                                zIndex={1000}
                                                title="确定是否删除?"
                                                overlayClassName={styles.PopconfirmCustomer}
                                                getPopupContainer={triggerNode => triggerNode.closest('.ant-card-body')}
                                                onConfirm={() => {
                                                    handleDelete(index);
                                                }}
                                            >
                                                <Tooltip
                                                    styles={{ zIndex: 10 }}
                                                    title="删除"
                                                    key={item.edit}
                                                    arrowPointAtCenter
                                                    getPopupContainer={triggerNode => triggerNode}
                                                >
                                                    <BizIcon
                                                        type="DeleteIcon"
                                                        style={{
                                                            fontSize: `${20}px`,
                                                            lineHeight: `${20}px`,
                                                            cursor: 'pointer'
                                                        }}
                                                        className={cn(styles.iconCursor, styles.deleteIcon)}
                                                    />
                                                </Tooltip>
                                            </Popconfirm>
                                            {/* 下面这个key用于强制更新节点 */}
                                        </div>
                                    </>
                                ) : null}
                            </div>
                        )}
                    </Form.Item>
                </div>
            ))}

            {!disabled && (
                <div className={cn(styles.add, allowAdd ? '' : styles.addBtnGray)} onClick={handleAddPanel}>
                    +添加问题
                </div>
            )}
        </Spin>
    );
};

export default CustomAddV2;
